package services;

import java.util.Collection;

import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import repositories.TeamRepository;
import domain.Administrator;
import domain.Team;

@Transactional
@Service
public class TeamService {
	
	// Managed repository
	
	@Autowired
	private TeamRepository groupRepository;
	
	// Supporting services
	
	@Autowired
	private ActorService actorService;
	
	// Simple CRUD methods
	
	public Team create(){
		checkPrincipal();
		Team group = new Team();
		
		return group;
	}
	
	public void save(Team group){
		checkPrincipal();
		Assert.notNull(group);
		if(group.getId()!=0){
			Assert.isTrue(group.getUsers().size()==0,"group.commit.error.users");
		}
		groupRepository.save(group);
	}
	
	public void delete(Team group){
		checkPrincipal();
		Assert.notNull(group);
		Assert.isTrue(group.getId() != 0);
		Assert.isTrue(groupRepository.exists(group.getId()));
		Assert.isTrue(group.getUsers().size()==0,"group.save.error.users");
		
		groupRepository.delete(group);
	}
	
	// Other business methods -------------------------------------------------

	public void checkPrincipal(){
		Assert.isTrue(actorService.findByPrincipal() instanceof Administrator);
	}
	
	public Team findOne(int groupId){
		checkPrincipal();
		return groupRepository.findOne(groupId);
	}

	public Collection<Team> findAllGroups(){
		checkPrincipal();
		return groupRepository.findAllGroups();
	}


}
